package cn.edu.xmu.oomall.customer.controller;



import cn.edu.xmu.javaee.core.aop.Audit;
import cn.edu.xmu.javaee.core.aop.LoginUser;
import cn.edu.xmu.javaee.core.model.ReturnNo;
import cn.edu.xmu.javaee.core.model.ReturnObject;
import cn.edu.xmu.javaee.core.model.dto.UserDto;
import cn.edu.xmu.javaee.core.model.vo.PageVo;
import cn.edu.xmu.javaee.core.util.CloneFactory;
import cn.edu.xmu.oomall.customer.controller.dto.AddressDto;
import cn.edu.xmu.oomall.customer.controller.vo.AddressVo;
import cn.edu.xmu.oomall.customer.dao.bo.Address;
import cn.edu.xmu.oomall.customer.service.AddressService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController /*Restful的Controller对象*/
@RequestMapping(value = "/address", produces = "application/json;charset=UTF-8")
@RequiredArgsConstructor
@Slf4j
public class AddressController {

    private final AddressService addressService;


    @GetMapping()
    @Audit(departName = "customer")
    public ReturnObject getAddress(@LoginUser UserDto user,
                                   @RequestParam(required = false, defaultValue = "1") Integer page,
                                   @RequestParam(required = false, defaultValue = "10") Integer pageSize) {

        List<Address> addressList = addressService.retrieveAddress(user, page, pageSize);
        List<AddressVo> addressVos = addressList.stream()
                .map(bo -> CloneFactory.copy(new AddressVo(bo), bo))
                .collect(java.util.stream.Collectors.toList());
        return new ReturnObject(new PageVo<>(addressVos, page, pageSize));
    }


    @PutMapping("/{id}/default")
    @Audit(departName = "customer")
    public ReturnObject setDefaultAddress(@PathVariable Long id, @LoginUser UserDto user) {

        addressService.setDefaultAddress(id, user);
        return new ReturnObject(ReturnNo.OK);
    }


    @PutMapping("/{id}")
    @Audit(departName = "customer")
    public ReturnObject setAddress(@PathVariable Long id,
                                   @LoginUser UserDto user,
                                   @RequestBody AddressDto dto) {

        Address address = CloneFactory.copy(new Address(), dto);
        address.setId(id);
        addressService.setAddress(user, address);
        return new ReturnObject(ReturnNo.OK);
    }

    @DeleteMapping({"/{id}"})
    @Audit(departName = "customer")
    public ReturnObject delAddress(@PathVariable Long id, @LoginUser UserDto user) {

        addressService.delAddress(id, user);
        return new ReturnObject(ReturnNo.OK);
    }

}
